package com.nxuer.controllers.pkg01;

import com.alibaba.fastjson.JSON;
import lombok.Data;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Data
class SetApiBody {
    int id;
    int status;
}

@Data
class QueryBody {
    String deviceKey;
    int opt;
    int relayId;
}

@RestController
@RequestMapping("/RestfulApi")
public class SetRelays {

    @PostMapping("/SetRelays")
    String setter(@RequestBody SetApiBody req) {


        try {
            QueryBody qb =  new QueryBody();
            qb.setDeviceKey(req.id < 20 ? "827" : "23272");
            qb.setRelayId(req.id % 10);
            qb.setOpt(req.status);
            String reqBody = JSON.toJSONString(qb);
            //System.out.println(qb.toString());
//        RestTemplate restClient = new RestTemplate();

//        System.out.println(reqBody);
//        MultiValueMap<String, String> headers = new HttpHeaders();
//        headers.set("userId", "9372");
//        HttpEntity<String> request = new HttpEntity<>(reqBody, headers);
//        System.out.println(JSON.toJSONString(request));
//        String rep = restClient.postForEntity(url, request, String.class).getBody();

            String url = "http://iot.0531yun.cn/wsjc/app/SetRelays";
            HttpPost post = new HttpPost(url);
            post.setHeader("userId", "9372");
            post.setEntity(new StringEntity(reqBody, "application/json", "UTF-8"));
//            for (byte b : post.getEntity().getContent().readAllBytes()) {
//                System.out.print((char)b);
//            }
//            System.out.println();
//            System.out.println(Arrays.toString(post.getAllHeaders()));
            HttpClient httpClient = HttpClients.createDefault();
            HttpResponse httpResponse = httpClient.execute(post);
            String rep = EntityUtils.toString(httpResponse.getEntity());
            System.out.println(rep);
            return rep;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "{\"code\": 1001, \"message\": \"boom\"}";
    }
}
